package com.dangfei.servlet;

import com.dangfei.dao.UserDao;
import com.dangfei.daoimp.UserDaoimp;
import com.dangfei.model.User;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Register
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userID = request.getParameter("userid");
        String username = request.getParameter("username");
        String password = request.getParameter("userpwd");
        String userphone = request.getParameter("userphone");
        String userclass = request.getParameter("classid");
        //设置编码输出格式
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        String res = "{\"code\":201,\"msg\":\"参数缺失\"}";
        //判断用户名和密码是否均不为空
        if ((username == null) || (password == null) || (userID == null) || (userphone == null) || (userclass == null)) {
        } else {
            User user = new User();
            user.setUserID(Integer.parseInt(userID));
            user.setUserName(username);
            user.setUserPwd(password);
            user.setUserBalance((request.getParameter("balance") == null) ? 0 : Integer.parseInt(request.getParameter("balance")));
            user.setUserType(0);
            user.setUserPhone(userphone);
            Date dNow = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            user.setUserRegtime(ft.format(dNow));
            user.setUserClassID(Integer.parseInt(userclass));
            UserDao userdao = new UserDaoimp();
            boolean reg = userdao.register(user);
            //判断登陆结果
            if (reg) {
                res = "{\"code\":200,\"msg\":\"注册成功!\",\"url\":\"index.jsp\"}";
            } else {
                res = "{\"code\":202,\"msg\":\"注册失败,可能是用户名重复！\"}";
            }
        }
        out.println(res);
    }

}
